package sunlight.util.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

public class LocalConfigurationFile implements ConfigurationFile{
	
	protected int Type;
	
	protected Properties Handler;
	protected File 	   File;

	public LocalConfigurationFile(){
		this.Handler = new Properties();
	}
	
	public LocalConfigurationFile(File path){
		this.Handler = new Properties(); 
	}
	
	public LocalConfigurationFile(File path, int type) throws InvalidPropertiesFormatException, FileNotFoundException, IOException{
		this.Handler = new Properties(); 
		this.Type = type;
		this.File = path;
		
		if(type == LocalConfigurationFile.CONFIG_FILE_XML){
			this.loadFromXML(new FileInputStream(path));
		}
		
		if(type == LocalConfigurationFile.CONFIG_FILE_PLAIN){
			this.loadFromPlainText(new FileInputStream(path));
		}
	}
	
	public void setTypeXML(){
		this.Type = LocalConfigurationFile.CONFIG_FILE_XML;
	}
	
	public void setTypePlain(){
		this.Type = LocalConfigurationFile.CONFIG_FILE_PLAIN;
	}
	
	public void loadFromXML(FileInputStream in) throws InvalidPropertiesFormatException, IOException{
		this.Handler.loadFromXML(in);
	}
	
	public void loadFromPlainText(FileInputStream in) throws IOException{
		this.Handler.load(in);
	}
	
	public Object get(String key){
		return this.Handler.get(key);
	}
	
	public Object get(String key, String defaultvalue){
		if(this.Handler.get(key) == null){
			return defaultvalue;
		}
		
		return this.Handler.get(key);
	}
	
	public void set(String key, String value){
		this.Handler.setProperty(key, value);
	}
	
	public void save() throws FileNotFoundException, IOException{
		this.save("");
	}
	
	public void save(String comments) throws FileNotFoundException, IOException{
		if(this.Type == LocalConfigurationFile.CONFIG_FILE_XML){
			this.Handler.storeToXML(new FileOutputStream(this.File), comments);
		}
		
		if(this.Type == LocalConfigurationFile.CONFIG_FILE_PLAIN){
			this.Handler.store(new FileOutputStream(this.File), comments);
		}
	}
}
